package cn.stimd.spring.aop.support;

import cn.stimd.spring.aop.Advisor;
import cn.stimd.spring.aop.MethodMatcher;
import cn.stimd.spring.aop.Pointcut;
import cn.stimd.spring.aop.PointcutAdvisor;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

/**
 * Created by Stimd
 * 项目地址：https://gitee.com/stimd/spring-wheel
 * 公众号：Java编程探微
 */
public class AopUtils {
    //获取被包装的类，如果是Cglib代理，则是当前实例的父类
    public static Class<?> getTargetClass(Object candidate) {
        return (ClassUtils.isCglibProxy(candidate) ? candidate.getClass().getSuperclass() : candidate.getClass());
    }


    //检查Advisor是否可以应用于指定类
    public static boolean canApply(Advisor advisor, Class<?> targetClass) {
        //IntroductionAdvisor略

        //PointcutAdvisor
        if (advisor instanceof PointcutAdvisor) {
            PointcutAdvisor pa = (PointcutAdvisor) advisor;
            return canApply(pa.getPointcut(), targetClass);
        }
        //Advisor失去切面特性，默认适用于所有类
        return true;
    }


    /**
     * 检查Pointcut是否可以应用于指定类
     */
    private static boolean canApply(Pointcut pointcut, Class<?> targetClass){
        //1. 检查ClassFilter和MethodMatcher是否匹配
        if (!pointcut.getClassFilter().matches(targetClass)) {
            return false;
        }

        MethodMatcher methodMatcher = pointcut.getMethodMatcher();
        if(methodMatcher == MethodMatcher.TRUE){
            return true;
        }

        //如果是IntroductionAwareMethodMatcher，则强转（略）

        //2. 获取指定类的所有接口类型
        Set<Class<?>> classes = new LinkedHashSet<>(ClassUtils.getAllInterfacesForClassAsSet(targetClass));
        classes.add(targetClass);

        //3. 遍历当前类及接口的所有方法，只要有一个符合条件，则认为PointcutAdvisor适用当前类
        for (Class<?> clazz : classes) {
            Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz);
            for (Method method : methods) {
                if(methodMatcher.matches(method, targetClass)){
                    return true;
                }
            }
        }
        return false;
    }


    public static List<Advisor> findAdvisorsThatCanApply(List<Advisor> candidateAdvisors, Class<?> clazz) {
        if (candidateAdvisors.isEmpty()) {
            return candidateAdvisors;
        }
        List<Advisor> eligibleAdvisors = new LinkedList<>();
        //优先处理IntroductionAdvisor（略）

        for (Advisor candidate : candidateAdvisors) {
            if (canApply(candidate, clazz)) {
                eligibleAdvisors.add(candidate);
            }
        }
        return eligibleAdvisors;
    }
}
